package com.financial.business.integral.service.yd.impl;

import com.financial.business.integral.config.YDAccessTokenConfig;
import com.financial.business.integral.connector.SysconfigFeign;
import com.financial.business.integral.connector.YsServiceFeign;
import com.financial.business.integral.constants.FinancialPaymentIntegralEnumConstants;
import com.financial.business.integral.dao.FinancialYDPaymentIntegralDao;
import com.financial.business.integral.dto.FinancialYDIntegralPaymentDTO;
import com.financial.business.integral.service.yd.FinancialYDIntegralPaymentService;
import com.financial.business.integral.utils.HttpClientUtils;
import com.financial.business.integral.utils.JsonUtils;
import com.financial.business.integral.utils.RedisUtils;
import com.financial.business.integral.utils.ValidateUtils;
import com.financial.business.integral.utils.apiresult.ApiResult;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Davidbieber
 * @description 金融中心积分代付业务接口实现类
 * @email davidbieber@163.com
 * @date 2019/12/12 8:55 AM
 */
@Service
public class FinancialYDIntegralPaymentServiceImpl implements FinancialYDIntegralPaymentService {

    protected static final Logger logger = LoggerFactory.getLogger(FinancialYDIntegralPaymentServiceImpl.class);

    @Autowired
    private SysconfigFeign sysconfigFeign;

    @Autowired
    private YDAccessTokenConfig ydAccessTokenConfig;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private FinancialYDPaymentIntegralDao financialYDPaymentIntegralDao;

    @Autowired
    private HttpClientUtils httpClientUtils;

    @Autowired
    private YsServiceFeign ysServiceFeign;

    @Override
    public ApiResult payment(String requestParam) {
        logger.info("FinancialYDIntegralPaymentServiceImpl.payment()-----获取积分代付JSON为：" + requestParam);
        FinancialYDIntegralPaymentDTO financialYDIntegralPaymentDTO = JsonUtils.convertBean(requestParam, FinancialYDIntegralPaymentDTO.class);
        Map<String, Object> params = JsonUtils.jsonToMap(requestParam);
        /*支付数额*/
        Object tempParam = params.get("integral_amount");
        String integralAmountStr = tempParam == null ? null : tempParam.toString();
        /*银行名称*/
        tempParam = params.get("bank_name");
        String bankName = tempParam == null ? null : tempParam.toString();
        /*订单说明*/
        tempParam = params.get("subject");
        String subject = tempParam == null ? null : tempParam.toString();
        /*银行城市*/
        tempParam = params.get("bank_city");
        String bankCity = tempParam == null ? null : tempParam.toString();
        /*银行账户名称*/
        tempParam = params.get("bank_account_name");
        String bankAccountName = tempParam == null ? null : tempParam.toString();
        /*银行卡类型*/
        /*debit：借记卡，credit：贷记卡，unit:单位结算卡*/
        tempParam = params.get("bank_card_type");
        String bankCardType = tempParam == null ? null : tempParam.toString();
        /*银行账户类型*/
        /*corporate：对公账户;personal：对私账户*/
        tempParam = params.get("bank_account_type");
        String bankAccountType = tempParam == null ? null : tempParam.toString();
        /*银行账户好*/
        tempParam = params.get("bank_account_no");
        String bankAccountNo = tempParam == null ? null : tempParam.toString();
        /*支付交易单号*/
        tempParam = params.get("out_trade_no");
        String outTradeNo = tempParam == null ? null : tempParam.toString();
        /*业务编码*/
        /*支付交易单号*/
        tempParam = params.get("business_code");
        String businessCode = tempParam == null ? null : tempParam.toString();
        /*币种代码*/
        /*支付交易单号*/
        tempParam = params.get("currency");
        String currency = tempParam == null ? null : tempParam.toString();
        if (org.apache.commons.lang3.StringUtils.isBlank(integralAmountStr)
                || org.apache.commons.lang3.StringUtils.isBlank(bankName) || StringUtils.isBlank(subject)
                || org.apache.commons.lang3.StringUtils.isBlank(bankCity) || org.apache.commons.lang3.StringUtils.isBlank(bankAccountName)
                || org.apache.commons.lang3.StringUtils.isBlank(bankCardType) || org.apache.commons.lang3.StringUtils.isBlank(bankAccountType)
                || org.apache.commons.lang3.StringUtils.isBlank(bankAccountNo) || org.apache.commons.lang3.StringUtils.isBlank(outTradeNo)
                || org.apache.commons.lang3.StringUtils.isBlank(businessCode) || org.apache.commons.lang3.StringUtils.isBlank(currency)) {
            /*对所传字段进行非空校验判断*/
            return ApiResult.failure(ValidateUtils.validateProperty(financialYDIntegralPaymentDTO));
        }
        BigDecimal integralAmount = new BigDecimal(integralAmountStr).setScale(2, RoundingMode.HALF_UP);
        Map<String, Object> bizContentMap = new HashMap<>();
        /*根据订单号截取商户日期*/
        String shopdate = outTradeNo.substring(0, 8);
        bizContentMap.put("out_trade_no", outTradeNo);
        bizContentMap.put("total_amount", integralAmount);
        bizContentMap.put("subject", subject);
        bizContentMap.put("bank_name", bankName);
        bizContentMap.put("bank_city", bankCity);
        bizContentMap.put("bank_account_no", bankAccountNo);
        bizContentMap.put("bank_account_name", bankAccountName);
        bizContentMap.put("bank_account_type", bankAccountType);
        bizContentMap.put("bank_card_type", bankCardType);
        bizContentMap.put("shopdate", shopdate);
        bizContentMap.put("business_code", businessCode);
        bizContentMap.put("currency", currency);
        /*将map装换成json调用银盛代付*/
        String bizContentJson = JsonUtils.toJSon(bizContentMap);
        logger.info("FinancialBalanceYsPaymentServiceImpl.payment()------调用银盛代付之前组装json为:" + bizContentJson);
        ApiResult paymentApi = ysServiceFeign.payment(bizContentJson);
        logger.info("FinancialBalanceYsPaymentServiceImpl.payment()------调用银盛代付返回为:" + paymentApi);
        /*对返回的参数判断进行落库处理*/
        String returnMsg = (String) paymentApi.getResult();
        /*更改数据库状态*/
        Map<String, Object> condMap = new HashMap<>();
        condMap.put("outTradeNo", outTradeNo);
        condMap.put("returnMessage", returnMsg);
        condMap.put("gmtModified", new Date());
        if (paymentApi.getCode() == FinancialPaymentIntegralEnumConstants.ENUM_CODE_SUC && (returnMsg != null && returnMsg != "")) {
            condMap.put("state", FinancialPaymentIntegralEnumConstants.ENUM_STATE_SUC);
            int updateState = financialYDPaymentIntegralDao.updateInfo(condMap);
            if (updateState > 0) {
                logger.info("FinancialBalanceYsPaymentServiceImpl.payment()------代付同步回执信息更改状态成功！");
                return ApiResult.success(returnMsg);
            }
        } else {
            condMap.put("state", FinancialPaymentIntegralEnumConstants.ENUM_STATE_FAIL);
            financialYDPaymentIntegralDao.updateInfo(condMap);
            logger.info("FinancialBalanceYsPaymentServiceImpl.payment()------代付同步回执信息有误！" + paymentApi);
            return ApiResult.failure(paymentApi);
        }
        return ApiResult.success(requestParam);
    }

    @Override
    public String query(Map<String, Object> paramMap) {
        return financialYDPaymentIntegralDao.query(paramMap);
    }
}
